package server

import (
	"embed"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	"html/template"
	"io/fs"
	"melon/server/initialize"
	"melon/server/utils/template_func"
	"net/http"
)

//go:embed assets
var local embed.FS

//go:embed view
var tmpl embed.FS

type embedFileSystem struct {
	http.FileSystem
}

func (e embedFileSystem) Exists(prefix, path string) bool {
	_, err := e.Open(path)
	if err != nil {
		return false
	}
	return true
}

func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
	fsys, err := fs.Sub(fsEmbed, targetPath)
	if err != nil {
		panic(err)
	}
	return embedFileSystem{
		FileSystem: http.FS(fsys),
	}
}

func InitWebRouter() *gin.Engine {

	// 初始化配置
	initialize.InitConfig()

	var Router = gin.Default()
	Router.SetFuncMap(template.FuncMap{
		"split": template_func.Split,
		"md5":   template_func.MD5,
	})
	// 静态文件配置
	setHTMLFsTemplate(Router, tmpl, "view/**/*.html")
	Router.StaticFS("/assets", EmbedFolder(local, "assets"))

	// 初始化路由
	initialize.InitRoute(Router)
	return Router
}

func setHTMLFsTemplate(router *gin.Engine, fs fs.FS, patterns ...string) {
	tmpl := template.Must(template.New("").Funcs(router.FuncMap).ParseFS(fs, patterns...))
	router.SetHTMLTemplate(tmpl)
}
